#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Any

from matplotlib import pyplot as plt
from pylab import mpl

from cta.config.base_config import BaseConfig
from cta.interface.action.picture.abstract_picture_action import AbstractPictureAction
from web.domain.responsibility_chain_dto import ResponsibilityChainDto
from web.manager.log_manager import LogManager
from web.models.quant2_account_log import Quant2AccountLog

Logger = LogManager.get_logger(__name__)

class CreateQuant2AccountLogProfitAndLossRatePictureAction(AbstractPictureAction):
    """
    根据表quant2_account_log中每个账号的总资金，生成折线图
    """

    def exec(self, responsibility_chain_dto: ResponsibilityChainDto = None) -> Any:
        Logger.info("根据表quant2_account_log中每个账号的总资金，生成折线图")

        # 根据开始时间、结束时间查询记录，并按照date_和account_name列升序排列
        quant2_account_log_list: list[Quant2AccountLog] = self.quant2_account_log_dao.find_by_begin_date_and_end_date_order_by_date_and_account_name(BaseConfig.Begin_Date, BaseConfig.End_Date)
        if quant2_account_log_list is not None and len(quant2_account_log_list):
            date_list: list[str] = list()
            account_name_1_profit_and_loss_rate_list: list[float] = list()
            account_name_2_profit_and_loss_rate_list: list[float] = list()
            account_name_3_profit_and_loss_rate_list: list[float] = list()
            account_name_4_profit_and_loss_rate_list: list[float] = list()
            account_name_1: str = quant2_account_log_list[0].account_name
            account_name_2: str = quant2_account_log_list[1].account_name
            account_name_3: str = quant2_account_log_list[2].account_name
            account_name_4: str = quant2_account_log_list[3].account_name

            for index, quant2_account_log in enumerate(quant2_account_log_list):
                if (index + 1) % 4 == 1:
                    date_list.append(quant2_account_log.date_)
                    account_name_1_profit_and_loss_rate_list.append(
                        float(quant2_account_log.total_assets / BaseConfig.Create_Quant2_Account_Log_Profit_And_Loss_Rate_Picture_Init_Funds * 100))
                if (index + 1) % 4 == 2:
                    account_name_2_profit_and_loss_rate_list.append(
                        float(quant2_account_log.total_assets / BaseConfig.Create_Quant2_Account_Log_Profit_And_Loss_Rate_Picture_Init_Funds * 100))
                if (index + 1) % 4 == 3:
                    account_name_3_profit_and_loss_rate_list.append(
                        float(quant2_account_log.total_assets / BaseConfig.Create_Quant2_Account_Log_Profit_And_Loss_Rate_Picture_Init_Funds * 100))
                if (index + 1) % 4 == 0:
                    account_name_4_profit_and_loss_rate_list.append(
                        float(quant2_account_log.total_assets / BaseConfig.Create_Quant2_Account_Log_Profit_And_Loss_Rate_Picture_Init_Funds * 100))

            # 创建一个新的图表
            fig, ax = plt.subplots(figsize=(18, 8))

            # 关闭交互模式
            plt.ioff()

            mpl.rcParams["font.sans-serif"] = ["SimHei"]

            # 创建折线图
            ax.plot(date_list, account_name_1_profit_and_loss_rate_list, label=account_name_1, lw=0.5, marker='o', color='red')
            ax.plot(date_list, account_name_2_profit_and_loss_rate_list, label=account_name_2, lw=0.5, marker='o', color='blue')
            ax.plot(date_list, account_name_3_profit_and_loss_rate_list, label=account_name_3, lw=0.5, marker='o', color='green')
            ax.plot(date_list, account_name_4_profit_and_loss_rate_list, label=account_name_4, lw=0.5, marker='o', color='black')
            plt.legend()
            plt.title('根据表quant2_account_log中每个账号的总资金，生成折线图')
            plt.xlabel('时间')
            plt.ylabel('收益率')

            # 分辨率
            plt.rcParams['savefig.dpi'] = 300

            # 显示图例
            # plt.legend()

            # 保存图表
            plt.savefig(BaseConfig.Create_Quant2_Account_Log_Profit_And_Loss_Rate_Picture_Path)

            # 显示图表
            # plt.show()

            # 关闭图表
            plt.close()

        super().exec(responsibility_chain_dto)